<template>
  <div class="home">
    <div class="content">
      <div class="header">
        <el-page-header content="编辑页面" @back="goBack"></el-page-header>
      </div>
      <div class="selectMoudle">
        <div>
          <span class="text">模块</span>
          <el-radio-group v-model="editorData.radio1" fill="#1d2f70">
            <el-radio-button v-for="(item, index) in radio" :label="item.label" :key="index"></el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button class="sendBtn" @click="send">
            发布
            <i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </div>
      </div>
      <div class="Imagetitele">
        <div class="textSize">添加题图</div>
      </div>
      <div class="titleImage">
        <div class="algin">
          <el-upload
            accept="image/png, image/jpg, image/jpeg"
            class="avatar-uploader"
            :action="api.imgManage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="editorData.titleImageUrl" :src="editorData.titleImageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </div>
      <!-- 分享文章 -->
      <div class="shareList">
        <div class="shareTitle">文章分享</div>
        <div>
          <el-button type="primary" size="small" @click="shareFormVisible = true">新增分享</el-button>
        </div>
        <el-card class="box-card" v-if="editorData.shareArticle.length > 0">
          <div v-for="(item,index) in editorData.shareArticle" :key="index" class="text item">
            <div>
              <span class="titleShare">分享标题:</span>
              <span class="itemText">{{item.title}}</span>
              <span class="titleShare">分享链接:</span>
              <span class="itemText">{{item.url}}</span>
            </div>
            <div>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="editbox(index)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="delebox(index)"
              ></el-button>
            </div>
          </div>
        </el-card>
      </div>
      <!-- 新增分享 -->
      <el-dialog title="新增" :visible.sync="shareFormVisible" width="30%">
        <el-form :model="shareForm">
          <el-form-item label="分享标题">
            <el-input v-model="shareForm.title" autocomplete="off" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="分享链接">
            <el-input v-model="shareForm.url" autocomplete="off" placeholder="请输入链接"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="shareFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="newShareFrom">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改分享 -->
      <el-dialog title="修改" :visible.sync="editshareFormVisible" width="30%">
        <el-form :model="editShareForm">
          <el-form-item label="分享标题">
            <el-input v-model="editShareForm.title" autocomplete="off" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="分享链接">
            <el-input v-model="editShareForm.url" autocomplete="off" placeholder="请输入链接"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="shareFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="editShareFrom">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 富文本 -->
      <div class="inputBox">
        <input type="text" placeholder="输入标题" v-model="editorData.title" />
      </div>
      <div class="editor">
        <textEditor
          @EditorChange="editorChange"
          @uploadImageChange="uploadImageChange"
          :oldcontent="editorData.html"
          :oldremoveIds="editorData.deleImgId"
        ></textEditor>
      </div>
    </div>
  </div>
</template>

<script>
// import axios from "axios";
import textEditor from "../../components/quillEditor";
import { textReplace } from "../../common/textReplace";
import { get_draft, put_draft, delete_draft } from "../../api/draft";
import { post_article } from "../../api/article";
import { post_delectImg } from "@/api/deleteTheInterface";
import { rich_text_img, rich_text_img_prefix } from "../../utils/global";
export default {
  name: "Editor",
  data() {
    return {
      editorData: {
        radio1: "珠海港圈",
        title: "",
        titleImageUrl: "",
        html: "",
        deleImgId: [],
        textReplace: "",
        deletTitleImageUrl: [],
        shareArticle: []
      },
      headers: { Authorization: "Bearer " + this.$store.getters.token },
      timer: null,
      radio: [
        {
          name: "珠海港圈",
          label: "珠海港圈"
        }
        // ,
        //     {
        //       name: "创新建议",
        //       label: "创新建议"
        //     }
      ],
      api: {
        imgManage: rich_text_img,
        rich_text_img_prefix
      },
      shareFormVisible: false,
      editshareFormVisible: false,
      shareForm: {
        title: "",
        url: ""
      },
      editShareForm: {
        title: "",
        url: ""
      },
      editIndex: null
    };
  },
  components: {
    textEditor
  },
  async created() {
    console.log(this.$route.query._id);

    if (!this.$route.query._id) {
      this.$router.push({
        path: "/home"
      });
      return;
    }
    let editData = await get_draft({ query: { _id: this.$route.query._id } });
    console.log("editData", editData.data[0]);
    this.editorData = editData.data[0];
    this.$message({
      showClose: true,
      message: "已自动保存成功至草稿箱",
      type: "success"
    });
    clearInterval(this.timer);
    this.timer = null;
    this.setTimer();
  },
  destroyed: function() {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    setTimer() {
      let time = 1000 * 30;
      if (this.timer == null) {
        this.timer = setInterval(async () => {
          this.editorData.editTime = new Date();
          await put_draft({
            query: { _id: this.editorData._id },
            update: {
              $set: this.editorData
            }
          });
          this.$message({
            showClose: true,
            message: "自动保存成功",
            type: "success"
          });
        }, time);
      }
    },
    async uploadImageChange() {
      await put_draft({
        query: { _id: this.editorData._id },
        update: {
          $set: this.editorData
        }
      });
      this.$message({
        showClose: true,
        message: "自动保存成功",
        type: "success"
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    handleAvatarSuccess(res, file) {
      console.log("handleAvatarSuccess", file, this.editorData);

      // this.editorData.titleImageUrl = URL.createObjectURL(file.raw);
      if (this.editorData.titleImageUrl) {
        let name = this.editorData.titleImageUrl.replace(
          this.api.rich_text_img_prefix,
          ""
        );
        this.editorData.deletTitleImageUrl.push(name);
      }
      this.editorData.titleImageUrl = file.response.url;
      this.uploadImageChange();
      console.log("handleAvatarSuccess2222", this.editorData);
    },
    uploadSectionFile: function(param) {
      //自定义文件上传
      console.log("param", param);
      // var fileObj = param.file;
      var reader = new FileReader(); //调用FileReader
      reader.readAsDataURL(param.file); //将文件读取为 DataURL(base64)
      var that = this;
      reader.onload = function(evt) {
        //读取操作完成时触发。
        that.editorData.titleImageUrl = evt.target.result;
      };
    },
    editorChange(data) {
      this.editorData.html = data.html;
      if (this.editorData.deleImgId.length != data.removeIds.length) {
        this.uploadImageChange();
      }
      this.editorData.deleImgId = data.removeIds;
      // this.editorData.textReplace = textReplace(data.html);
      console.log("改变后", this.editorData);
    },
    //发布文章
    async send() {
      if (this.editorData.titleImageUrl == "") {
        return this.$alert("请添加题图", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      if (this.editorData.title == "") {
        return this.$alert("请完善文章标题", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      if (this.editorData.html == "") {
        return this.$alert("请完善文章内容", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let deleArr = this.editorData.deleImgId.concat(
        this.editorData.deletTitleImageUrl
      );
      console.log(deleArr);
      this.editorData.textReplace = textReplace(this.editorData.html);
      await post_article({
        articlename: this.editorData.title, //文章标题
        articleimg: this.editorData.titleImageUrl, //文章主图
        content: this.editorData.html, //富文本内容
        userid: this.$store.getters.userInfo._id, //用户id
        aeticletype: this.editorData.radio1, //文章类型
        textReplace: this.editorData.textReplace,
        shareArticle: this.editorData.shareArticle //分享文章
      });

      let dele = await delete_draft({
        query: {
          _id: this.editorData._id
        }
      });
      console.log("dele", dele);

      if (deleArr.length != 0) {
        await post_delectImg({
          deleImgArr: deleArr
        });
      }
      setTimeout(() => {
        loading.close();
        this.$message({
          showClose: true,
          message: "发布成功",
          type: "success"
        });
        this.$alert("文章已发布，请耐心等待审核", "提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.$router.go(-1);
          }
          // callback: action => {
          //   this.$message({
          //     type: "info",
          //     message: `action: ${action}`
          //   });
          // }
        });
        // this.$router.replace({
        //   path: "/personalCenter"
        // });
        this.$finish_taskdata(2, this.$store.getters.userInfo._id);
      }, 1000);
    },
    delebox(index) {
      this.$confirm("此操作将删除该分享, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.editorData.shareArticle.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {});
    },
    editbox(index) {
      this.editshareFormVisible = true;
      this.editIndex = index;
      this.editShareForm = JSON.parse(
        JSON.stringify(this.editorData.shareArticle[this.editIndex])
      );
    },
    editShareFrom() {
      if (this.editShareForm.title && this.editShareForm.url) {
        this.editorData.shareArticle[this.editIndex] = this.editShareForm;
        this.editShareForm = {
          title: "",
          url: ""
        };
        this.editshareFormVisible = false;
      } else {
        this.$alert("请完善内容", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
    },
    newShareFrom() {
      if (this.shareForm.title && this.shareForm.url) {
        this.editorData.shareArticle.push(this.shareForm);
        this.shareForm = {
          title: "",
          url: ""
        };
        this.shareFormVisible = false;
      } else {
        this.$alert("请完善内容", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  background: #fff;
}
.content {
  width: 100%;
  .header {
    margin: 0 auto;
    width: 1200px;
    margin-top: 20px;
  }
  .selectMoudle {
    margin: 0 auto;
    width: 1200px;
    margin-top: 40px;
    display: flex;
    justify-content: space-between;
    .text {
      font-size: 20px;
      font-weight: 700;
      color: #757575;
      margin-right: 20px;
    }
    .sendBtn {
      background: #1d2f70;
      border: #1d2f70;
      color: #fff;
      &:hover {
        background: rgb(53, 89, 180);
      }
    }
  }
  .Imagetitele {
    width: 1200px;
    margin: 0 auto;
    margin-top: 40px;
    .textSize {
      font-size: 27px;
      font-weight: 700;
      color: #757575;
    }
  }
  .titleImage {
    width: 1200px;
    margin: 0 auto;
    margin-top: 20px;
    .algin {
      width: 800px;
      margin: 0 auto;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 800px;
        height: 300px;
        line-height: 300px;
        text-align: center;
      }
      .avatar {
        width: 800px;
        display: block;
      }
    }
  }
  .inputBox {
    margin: 0 auto;
    width: 1200px;
    margin-top: 20px;
    input {
      outline-style: none;
      outline-style: none;
      border: 0px;
      border-bottom: 2px solid #ccc;
      width: 1200px;
      padding: 13px 14px;
      font-size: 28px;
      font-weight: 700;
      font-family: "Microsoft soft";
      box-sizing: border-box;
    }
  }
  .shareList {
    margin: 0 auto;
    width: 1200px;
    margin-top: 30px;
    .shareTitle {
      font-size: 18px;
      font-weight: 600;
      color: #757575;
      margin-bottom: 10px;
    }
    .text {
      font-size: 14px;
    }

    .item {
      padding: 10px 0;
      display: flex;
      justify-content: space-between;
    }

    .box-card {
      margin-top: 10px;
      // width: 480px;
    }
    .titleShare {
      margin-right: 10px;
      font-weight: 600;
    }
    .itemText {
      margin-right: 10px;
    }
  }
  // margin-top: -19px;
  padding: 20px;
  box-sizing: border-box;
  .editor {
    min-height: 500px;
    margin-top: 40px;
  }
}
</style>
